package com.vrv.netmgr.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * Servlet implementation class QRCodeServlet
 */
//@WebServlet("/QRCodeServlet")
public class QRCodeServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public QRCodeServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int onColor = 0xFF000000;
        int offColor = 0xFFFFFFFF;
        int intX = 320;
        int intY = 320;
        String sErr = "L";
        String sEnc = "UTF-8";
        String content = request.getScheme() + "://" + request.getHeader("host") + request.getServletContext().getContextPath() + "/edpdmupgrade/EDPDMClient.apk";
        System.err.println("{content:" + content + "}");

        Map hints = new HashMap();
        ErrorCorrectionLevel lErr;
        if (sErr.equals("H"))
            lErr = ErrorCorrectionLevel.H;
        else if (sErr.equals("Q"))
            lErr = ErrorCorrectionLevel.Q;
        else if (sErr.equals("M"))
            lErr = ErrorCorrectionLevel.M;
        else
            lErr = ErrorCorrectionLevel.L;
        hints.put(EncodeHintType.ERROR_CORRECTION, lErr);
        hints.put(EncodeHintType.CHARACTER_SET, sEnc);

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setContentType("image/png");
        ServletOutputStream rsp = response.getOutputStream();
        QRCodeWriter qrWriter = new QRCodeWriter();
        try {
            BitMatrix bitMatrix = qrWriter.encode(content, BarcodeFormat.QR_CODE, intX, intY, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, "png", rsp, new MatrixToImageConfig(onColor, offColor));
        } catch (WriterException e) {
            e.printStackTrace();
        }
        rsp.flush();
        rsp.close();
        response.flushBuffer();
    }

}
